package com.mairuide.transactionstreamcount.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mairuide._frame.base.BaseController;
import com.mairuide._frame.base.ModuleCode;
import com.mairuide.bill.DealFlow;
import com.mairuide.bill.DealFlowVo;
import com.mairuide.bill.utils.DateUtils;
import com.mairuide.bill.utils.ExcelUtil;
import com.mairuide.bill.utils.ExcelUtils;
import com.mairuide.datalog.ActionType;
import com.mairuide.datalog.DataOperationLogService;
import com.mairuide.datalog.ModuleFlag;
import com.mairuide.datalog.SystemFlag;
import com.mairuide.entity.PageResult;
import com.mairuide.entity.Result;
import com.mairuide.entity.StatusCode;
import com.mairuide.phone.PhoneRecord;
import com.mairuide.transactionstreamcount.DealFlowQueryDto;
import com.mairuide.transactionstreamcount.DealflowVO;
import com.mairuide.transactionstreamcount.MonthAnalysisDto;
import com.mairuide.transactionstreamcount.service.TransactionStreamCountService;

/**
 * Created by 敲代码的卡卡罗特
 * on 2018/12/4 11:11.
 * 交易流水统计
 */
@Controller
@CrossOrigin
@RequestMapping("/bill/stream")
public class TransactionStreamCountController extends BaseController {
    @Autowired
    TransactionStreamCountService transactionStreamCountService;

    @Resource
    private DataOperationLogService dataOperationLogService;

    @ModuleCode("billflow_lrzhtj")
    @RequestMapping(method= RequestMethod.GET,value = "inAccountStatistics")
    public Object inAccountStatistics(ModelMap model){
        return "/stream/inAccountStatistics";
    }

    @ModuleCode("billflow_lczhtj")
    @RequestMapping(method= RequestMethod.GET,value = "outAccountStatistics")
    public Object outAccountStatistics(ModelMap model){
        return "/stream/outAccountStatistics";
    }

    @ModuleCode("billflow_lrzttj")
    @RequestMapping(method= RequestMethod.GET,value = "inBodyStatistics")
    public Object inBodyStatistics(ModelMap model){
        return "/stream/inBodyStatistics";
    }

    @ModuleCode("billflow_lczttj")
    @RequestMapping(method= RequestMethod.GET,value = "outBodyStatistics")
    public Object outBodyStatistics(ModelMap model){
        return "/stream/outBodyStatistics";
    }

    @ModuleCode("billflow_jyrqtj")
    @RequestMapping(method= RequestMethod.GET,value = "inoutTimeStatistics")
    public Object inoutTimeStatistics(ModelMap model){
        return "/stream/inoutTimeStatistics";
    }

    @ModuleCode("billflow_jyytj")
    @RequestMapping(method= RequestMethod.GET,value = "inoutMonthStatistics")
    public Object inoutMonthStatistics(ModelMap model){
        return "/stream/inoutMonthStatistics";
    }

    @ModuleCode("billflow_jyztj")
    @RequestMapping(method= RequestMethod.GET,value = "inoutWeekStatistics")
    public Object inoutWeekStatistics(ModelMap model){
        return "/stream/inoutWeekStatistics";
    }

    @ModuleCode("billflow_jysjdtj")
    @RequestMapping(method= RequestMethod.GET,value = "inoutHourStatistics")
    public Object inoutHourStatistics(ModelMap model){
        return "/stream/inoutHourStatistics";
    }


    @RequestMapping(method= RequestMethod.GET,value = "monthAnalysisSingl")
    public Object monthAnalysisSingle(ModelMap model){
        return "/stream/monthAnalysisSingle";
    }
    @RequestMapping(method= RequestMethod.GET,value = "monthAnalydan")
    public Object monthAnalydan(ModelMap model){
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	String today = sdf.format(new Date());
    	Calendar c = Calendar.getInstance();
    	c.setTime(new Date());
        c.add(Calendar.MONTH, -3);
        Date y = c.getTime();
    	String yearsago = sdf.format(y);
    	model.addAttribute("today", today);
    	model.addAttribute("yearsago", yearsago);
        return "/stream/monthAnalydan";
    }
    @RequestMapping(method= RequestMethod.GET,value = "tierrelation")
    public Object tierrelation(ModelMap model){
        return "/stream/tierrelation";
    }

    @ModuleCode("monthAnalysisSingle")
    @RequestMapping(method= RequestMethod.GET,value = "monthAnalysisSingle")
    public Object monthAnaly(ModelMap model){
        return "/stream/monthAnaly";
    }

    @ModuleCode("billflow_zytj")
    @RequestMapping(method= RequestMethod.GET,value = "inoutAbstractStatistics")
    public Object inoutAbstractStatistics(ModelMap model){
        return "/stream/inoutAbstractStatistics";
    }

    @RequestMapping(method= RequestMethod.POST,value = "/inaccountstatistics/{page}/{size}")
    @ResponseBody
    public Result getInStreamAccountCount(@RequestBody DealFlowQueryDto df, @PathVariable int page, @PathVariable int size){
        return new Result(true, StatusCode.OK,"查询成功",transactionStreamCountService.getInStreamAccountCount(df.getMinMoney(),df.getMaxMoney(),df.getCaseId(),df.getCardList(),df.getRivalName(), page, size,df.getBeginTime(),df.getEndTime(),df.getSortName(),df.getSortOrder()));
    }
    /**流入卡号统计  easuUi版**/
    @RequestMapping(method= RequestMethod.POST,value = "/inaccountstatistics_easyui")
    @ResponseBody
    public PageResult getInStreamAccountCount_easyui( DealFlowQueryDto df){
        PageResult pageResult = transactionStreamCountService.getInStreamAccountCount_easyui(df);
        return pageResult;
    }

    @RequestMapping(method= RequestMethod.POST,value = "outaccountstatistics/{page}/{size}")
    @ResponseBody
    public Result getOutStreamAccountCount(@RequestBody DealFlowQueryDto df, @PathVariable int page, @PathVariable int size){
        return new Result(true, StatusCode.OK,"查询成功",transactionStreamCountService.getOutStreamAccountCount(df.getMinMoney(),df.getMaxMoney(),df.getCaseId(),df.getCardList(),df.getRivalName(), page, size,df.getBeginTime(),df.getEndTime(),df.getSortName(),df.getSortOrder()));
    }

    @RequestMapping(method= RequestMethod.POST,value = "outaccountstatistics_easyui")
    @ResponseBody
    public PageResult getOutStreamAccountCount_easyui(DealFlowQueryDto df){
        PageResult pageResult = transactionStreamCountService.getOutStreamAccountCount_easyui(df);
        return pageResult;
    }

    @RequestMapping(method= RequestMethod.POST,value = "inbodystatistics/{page}/{size}")
    @ResponseBody
    public Result getInStreamBodyCount(@RequestBody DealFlowQueryDto df, @PathVariable int page, @PathVariable int size){
        String caseId = request.getSession().getAttribute("caseId") == null?"":request.getSession().getAttribute("caseId").toString();
        return new Result(true, StatusCode.OK,"查询成功",transactionStreamCountService.getInStreamBodyCount(df.getMinMoney(),df.getMaxMoney(),caseId,df.getCardList(),df.getRivalName(), page, size,df.getBeginTime(),df.getEndTime(),df.getSortName(),df.getSortOrder()));
    }
    @RequestMapping(method= RequestMethod.POST,value = "outbodystatistics/{page}/{size}")
    @ResponseBody
    public Result getOutStreamBodyCount(@RequestBody DealFlowQueryDto df, @PathVariable int page, @PathVariable int size){
        String caseId = request.getSession().getAttribute("caseId") == null?"":request.getSession().getAttribute("caseId").toString();
        return new Result(true, StatusCode.OK,"查询成功",transactionStreamCountService.getOutStreamBodyCount(df.getMinMoney(),df.getMaxMoney(),caseId,df.getCardList(),df.getRivalName(), page, size,df.getBeginTime(),df.getEndTime(),df.getSortName(),df.getSortOrder()));
    }

    @RequestMapping(method= RequestMethod.POST,value = "timestatistics/{page}/{size}")
    @ResponseBody
    public Result getInOutStreamTimeCount(@RequestBody DealFlowQueryDto df, @PathVariable int page, @PathVariable int size){
        return new Result(true, StatusCode.OK,"查询成功",transactionStreamCountService.getInOutStreamTimeCount(df.getMinMoney(),df.getMaxMoney(),df.getCaseId(),df.getCardList(),df.getRivalName(), page, size,df.getBeginTime(),df.getEndTime(),df.getSortName(),df.getSortOrder()));
    }
    @RequestMapping(method= RequestMethod.POST,value = "timestatistics_easyui")
    @ResponseBody
    public PageResult getInOutStreamTimeCount_easyui(DealFlowQueryDto df){
        PageResult pageResult = transactionStreamCountService.getInOutStreamTimeCount_easyui(df);
        return pageResult;
    }

    @RequestMapping(method= RequestMethod.POST,value = "monthstatistics/{page}/{size}")
    @ResponseBody
    public Result getInOutStreamMonthCount(@RequestBody DealFlowQueryDto df, @PathVariable int page, @PathVariable int size){
        return new Result(true, StatusCode.OK,"查询成功",transactionStreamCountService.getInOutStreamMonthCount(df.getMinMoney(),df.getMaxMoney(),df.getCaseId(),df.getCardList(),df.getRivalName(), page, size,df.getBeginTime(),df.getEndTime(),df.getSortName(),df.getSortOrder()));
    }
    @RequestMapping(method= RequestMethod.POST,value = "monthstatistics_easyui")
    @ResponseBody
    public PageResult getInOutStreamMonthCount_easyui( DealFlowQueryDto df){
        PageResult pageResult = transactionStreamCountService.getInOutStreamMonthCount_easyui(df);
        return pageResult;
    }

    @RequestMapping(method= RequestMethod.POST,value = "moneyFlow")
    @ResponseBody
    public Map<String,Object> getMoneyFlow(String[] checkedAccount,String caseId,String beginTime,String endTime,Integer minMoney,Integer maxMoney){
        if (checkedAccount==null||caseId==null)return null;
        List<String> strings = Arrays.asList(checkedAccount);
        Map<String,Object> list = transactionStreamCountService.getMoneyFlow(strings,caseId,beginTime,endTime,minMoney,maxMoney);
        list.remove("excel");
        return list;
    }
    @RequestMapping(method= RequestMethod.POST,value = "moneyFlowPersonal")
    @ResponseBody
    public Map<String,Object> moneyFlowPersonal(DealFlowVo vo){
        Map<String,Object> list = transactionStreamCountService.moneyFlowPersonal(vo);
        return list;
    }
    
    @RequestMapping(method= RequestMethod.POST,value = "moneyFlowPersonalD3")
    @ResponseBody
    public Object moneyFlowPersonalD3(DealFlowVo dealFlow){
    	Map<String,Object> list = transactionStreamCountService.moneyFlowPersonalD3(dealFlow);
    	return list;
    }
    @RequestMapping(method= RequestMethod.POST,value = "moneyFlowPersonalData")
    @ResponseBody
    public Object moneyFlowPersonalData(DealFlowVo vo){
    	List<DealFlow> list = transactionStreamCountService.zjlxfx(vo);
    	long count = 0l;
    	if(list!=null && list.size()>0) {
    		count = list.size();
    	}
    	PageResult pageResult = new PageResult(count,list);
    	return pageResult;
    }
    @RequestMapping(method= RequestMethod.POST,value = "getRivals")
    @ResponseBody
    public Object getRivals(DealFlowVo vo){
    	List<Map<String, Object>> list = transactionStreamCountService.getRivals(vo);
    	return list;
    }
    @RequestMapping(method= RequestMethod.POST,value = "moneyFlowPersonalZzjg")
    @ResponseBody
    public Object moneyFlowPersonalZzjg(DealFlowVo vo){
    	Map<String, Object> list = transactionStreamCountService.moneyFlowPersonalZzjg(vo);
    	return list;
    }

    @RequestMapping(method= RequestMethod.POST,value = "abstractstatistics/{page}/{size}")
    @ResponseBody
    public Result getInOutStreamAbstractCount(@RequestBody DealFlowQueryDto df, @PathVariable int page, @PathVariable int size){
        return new Result(true, StatusCode.OK,"查询成功",transactionStreamCountService.getInOutStreamAbstractCount(df.getMinMoney(),df.getMaxMoney(),df.getCaseId(),df.getCardList(),df.getRivalName(), page, size,df.getBeginTime(),df.getEndTime(),df.getSortName(),df.getSortOrder(),df.getShowType()));
    }
    @RequestMapping(method= RequestMethod.POST,value = "abstractstatistics_easyui")
    @ResponseBody
    public PageResult getInOutStreamAbstractCount_easyui(DealFlowQueryDto df){
        PageResult pageResult = transactionStreamCountService.getInOutStreamAbstractCount_easyui(df);
        return pageResult;
    }

    @RequestMapping(method= RequestMethod.GET,value = "bankstatistics")
    public Object bankAccountStatistics(ModelMap model){
        return "/stream/transactionbankstatistics";
    }

    @RequestMapping(value = "/bank/statistics")
    @ResponseBody
    public Object outAccountStatistics(String minMoney,String maxMoney,ModelMap model,String sort,String order,
                                       @RequestParam(required = false) String rivalName, int page, int rows,
                                       @RequestParam(required = false,value = "endTime")String endTime,
                                       @RequestParam(required = false,value = "startTime")String startTime,String cards,String caseId){
        return transactionStreamCountService.getBankStatisticsList(minMoney,maxMoney,cards, caseId,rivalName,page,rows,startTime,endTime,sort,order);
    }



    @RequestMapping("/export/{flag}")
    @ResponseBody
    public void billExport(String minMoney,String maxMoney,HttpServletResponse response ,@PathVariable Integer flag ,@RequestParam(required = false) String rivalName,@RequestParam(required = false)String beginTime,@RequestParam(required = false)String endTime,@RequestParam(defaultValue = "null" )String cardList,String caseId) throws Exception {
        // 生成导出excel名称
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = "银行账单账号统计" + dateFormat.format(date);
        if (flag==0){
            fileName="流入卡号统计";
        }else if (flag==1){
            fileName="流出卡号统计";
        }else if (flag==4){
            fileName="交易日期统计";
        }else if (flag==5){
            fileName="交易月统计";
        }else if (flag==8){
            fileName="摘要统计";
        }else if (flag==9){
            fileName="交易银行统计";
        }
//        String caseManageId = request.getSession().getAttribute("caseId") == null?"":request.getSession().getAttribute("caseId").toString();
        DealFlowQueryDto dto = new DealFlowQueryDto();
        dto.setCaseId(caseId);
        dto.setCardList(cardList);
        dto.setMinMoney(minMoney);
        dto.setMaxMoney(maxMoney);
        dto.setRivalName(rivalName);
        dto.setPage(1);
        dto.setRows(Integer.MAX_VALUE);
        dto.setBeginTime(beginTime);
        dto.setEndTime(endTime);

        //设置导出Excel标题
        String[] titles = null;
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List exportData =new ArrayList();
        //遍历导出Excel的内容
        switch (flag){
            case 0:{ //流入账号统计
                titles = new String[]{"交易对手", "交易对手账号", "交易总金额", "交易总次数", "净流入金额", "流入金额", "流入金额比", "流入次数", "流入次数比"};;
                list=transactionStreamCountService.getInStreamAccountCount_easyui(dto).getRows();
                exportData=getExportData(list,0);
                break;
            }
            case 1:{ //流出账号统计
                titles = new String[]{"交易对手", "交易对手账号", "交易总金额", "交易总次数", "净流出金额", "流出金额", "流出金额比", "流出次数", "流出次数比"};;
                list=transactionStreamCountService.getOutStreamAccountCount_easyui(dto).getRows();
                exportData=getExportData(list,1);
                break;
            }
           /* case 2:{ //流入主体统计
                titles = new String[]{"交易对手", "交易总金额", "交易总次数", "净流入出金额", "流入金额", "流入金额比", "流入次数", "流入次数比"};;
                list=transactionStreamCountService.getInStreamBodyCount_easyui(dto).getRows();
                exportData=getExportData(list,2);
                break;
            }
            case 3:{ //流出主体统计
                titles = new String[]{"交易对手",  "交易总金额", "交易总次数", "净流出金额", "流出金额", "流出金额比", "流出次数", "流出次数比"};;
                list=transactionStreamCountService.getOutStreamBodyCount_easyui(dto).getRows();
                exportData=getExportData(list,3);
                break;
            }*/
            case 4:{ //交易日期统计
                titles = new String[]{"日期","交易对手卡号","交易对手", "交易总金额", "交易总次数", "净流入金额", "流入金额", "流入金额比", "流入次数", "流入次数比", "流出金额", "流出金额比", "流出次数", "流出次数比"};;
                list=transactionStreamCountService.getInOutStreamTimeCount_easyui(dto).getRows();
                exportData=getExportData(list,4);
                break;
            }
            case 5:{ //交易月统计
                titles = new String[]{"月份", "交易对手卡号","交易对手",  "交易总金额", "交易总次数", "净流入金额", "流入金额", "流入金额比", "流入次数", "流入次数比", "流出金额", "流出金额比", "流出次数", "流出次数比"};;
                list=transactionStreamCountService.getInOutStreamMonthCount_easyui(dto).getRows();
                exportData=getExportData(list,5);
                break;
            }
            case 8:{ //摘要统计
                titles = new String[]{"摘要",  "交易次数", "交易次数比", "交易金额", "交易金额比"};
                list=transactionStreamCountService.getInOutStreamAbstractCount_easyui(dto).getRows();
                exportData=getExportData(list,8);
                break;
            }
            case 9:{ //银行统计
                titles = new String[]{"归属银行",  "对方机构号", "对方机构名称","交易次数","交易次数比", "交易金额", "交易金额比"};
                list=transactionStreamCountService.getBankStatisticsList(minMoney,maxMoney,cardList,caseId,rivalName,1,Integer.MAX_VALUE,beginTime,endTime,null,null).getRows();
                exportData=getExportData(list,9);
                break;
            }

        }
        // 把导出的内容写入到流里面
        byte[] content = ExcelUtil.writeExcel(titles, exportData);
        InputStream is = new ByteArrayInputStream(content);

        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + ExcelUtils.toUtf8String(fileName+".xls"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
            //插入导出日志
    		dataOperationLogService.save(null, super.getLoginUser(), new DealFlow(), new DealFlow(), SystemFlag.ZD, ModuleFlag.BILLSTATUS, ActionType.EXPORT);
        }
    }

    public List getExportData(List<Map<String, Object>> list,Integer which){
        List lists = new ArrayList<Map<Integer, String>>();
        switch (which){
            case 0 :{
                for (Map m : list) {
                    Map<Integer, Object> map = new HashMap<Integer, Object>();
                    //交易对手
                    map.put(0, m.get("ACCOUNT_RIVAL")==null?"":m.get("ACCOUNT_RIVAL"));
                    //交易对手账号
                    map.put(1, m.get("ACCOUNT_RIVAL_CARD")==null?"":m.get("ACCOUNT_RIVAL_CARD"));
                    //交易总金额
                    map.put(2, m.get("TOTALMONEY")==null?"":String.valueOf(m.get("TOTALMONEY")));
                    //交易总次数
                    map.put(3, m.get("TOTALNUMBER")==null?"":String.valueOf(m.get("TOTALNUMBER")));
                    //净流入金额
                    map.put(4, m.get("PUREINMONEY")==null?"":String.valueOf(m.get("PUREINMONEY")));
                    //流入金额
                    map.put(5, m.get("INMONEY")==null?"":String.valueOf(m.get("INMONEY")));
                    //流入金额比
                    map.put(6, m.get("INMONEYPER")==null?"":String.valueOf(m.get("INMONEYPER")));
                    //流入次数
                    map.put(7,m.get("INNUMBER")==null?"": String.valueOf(m.get("INNUMBER")));
                    //流入次数比
                    map.put(8,m.get("INNUMBERPER")==null?"": String.valueOf(m.get("INNUMBERPER")));
                    //把map集合添加到lists集合
                    lists.add(map);
                }
                break;
            }
            case 1:{
                for (Map m : list) {
                    Map<Integer, Object> map = new HashMap<Integer, Object>();
                    //交易对手
                    map.put(0, m.get("ACCOUNT_RIVAL")==null?"":m.get("ACCOUNT_RIVAL"));
                    //交易对手账号
                    map.put(1, m.get("ACCOUNT_RIVAL_CARD")==null?"":m.get("ACCOUNT_RIVAL_CARD"));
                    //交易总金额
                    map.put(2, m.get("TOTALMONEY")==null?"":String.valueOf(m.get("TOTALMONEY")));
                    //交易总次数
                    map.put(3, m.get("TOTALNUMBER")==null?"":String.valueOf(m.get("TOTALNUMBER")));
                    //净流出金额
                    map.put(4, m.get("PUREOUTMONEY")==null?"":String.valueOf(m.get("PUREOUTMONEY")));
                    //流出金额
                    map.put(5, m.get("OUTMONEY")==null?"":String.valueOf(m.get("OUTMONEY")));
                    //流出金额比
                    map.put(6, m.get("OUTMONEYPER")==null?"":String.valueOf(m.get("OUTMONEYPER")));
                    //流出次数
                    map.put(7,m.get("OUTNUMBER")==null?"": String.valueOf(m.get("OUTNUMBER")));
                    //流出次数比
                    map.put(8,m.get("OUTNUMBERPER")==null?"": String.valueOf(m.get("OUTNUMBERPER")));
                    //把map集合添加到lists集合
                    lists.add(map);
                }
                break;
            }
            case 2 :{
                for (Map m : list) {
                    Map<Integer, Object> map = new HashMap<Integer, Object>();
                    //交易对手
                    map.put(0, m.get("ACCOUNT_RIVAL")==null?"":m.get("ACCOUNT_RIVAL"));
                    //交易总金额
                    map.put(1, m.get("TOTALMONEY")==null?"":String.valueOf(m.get("TOTALMONEY")));
                    //交易总次数
                    map.put(2, m.get("TOTALNUMBER")==null?"":String.valueOf(m.get("TOTALNUMBER")));
                    //净流入金额
                    map.put(3, m.get("PUREINMONEY")==null?"":String.valueOf(m.get("PUREINMONEY")));
                    //流入金额
                    map.put(4, m.get("INMONEY")==null?"":String.valueOf(m.get("INMONEY")));
                    //流入金额比
                    map.put(5, m.get("INMONEYPER")==null?"":String.valueOf(m.get("INMONEYPER")));
                    //流入次数
                    map.put(6,m.get("INNUMBER")==null?"": String.valueOf(m.get("INNUMBER")));
                    //流入次数比
                    map.put(7,m.get("INNUMBERPER")==null?"": String.valueOf(m.get("INNUMBERPER")));
                    //把map集合添加到lists集合
                    lists.add(map);
                }
                break;
            }
            case 3:{
                for (Map m : list) {
                    Map<Integer, Object> map = new HashMap<Integer, Object>();
                    //交易对手
                    map.put(0, m.get("ACCOUNT_RIVAL")==null?"":m.get("ACCOUNT_RIVAL"));
                    //交易总金额
                    map.put(1, m.get("TOTALMONEY")==null?"":String.valueOf(m.get("TOTALMONEY")));
                    //交易总次数
                    map.put(2, m.get("TOTALNUMBER")==null?"":String.valueOf(m.get("TOTALNUMBER")));
                    //净流出金额
                    map.put(3, m.get("PUREOUTMONEY")==null?"":String.valueOf(m.get("PUREOUTMONEY")));
                    //流出金额
                    map.put(4, m.get("OUTMONEY")==null?"":String.valueOf(m.get("OUTMONEY")));
                    //流出金额比
                    map.put(5, m.get("OUTMONEYPER")==null?"":String.valueOf(m.get("OUTMONEYPER")));
                    //流出次数
                    map.put(6,m.get("OUTNUMBER")==null?"": String.valueOf(m.get("OUTNUMBER")));
                    //流出次数比
                    map.put(7,m.get("OUTNUMBERPER")==null?"": String.valueOf(m.get("OUTNUMBERPER")));
                    //把map集合添加到lists集合
                    lists.add(map);
                }
                break;
            }
            case 4:{
                for (Map m : list) {
                    Map<Integer, Object> map = new HashMap<Integer, Object>();
                    //日期
                    map.put(0, m.get("DATETIME")==null?"":m.get("DATETIME"));
                    //交易对手卡号
                    map.put(1, m.get("ACCOUNT_RIVAL_CARD")==null?"":String.valueOf(m.get("ACCOUNT_RIVAL_CARD")));
                    //交易对手
                    map.put(2, m.get("ACCOUNT_RIVAL")==null?"":String.valueOf(m.get("ACCOUNT_RIVAL")));
                    //总金额
                    map.put(3, m.get("TOTALMONEY")==null?"":String.valueOf(m.get("TOTALMONEY")));
                    //总次数
                    map.put(4, m.get("TOTALNUMBER")==null?"":String.valueOf(m.get("TOTALNUMBER")));
                    //净流入
                    map.put(5, m.get("PUREINMONEY")==null?"":String.valueOf(m.get("PUREINMONEY")));
                    //流入金额
                    map.put(6,m.get("INMONEY")==null?"": String.valueOf(m.get("INMONEY")));
                    //流入金额比
                    map.put(7,m.get("INMONEYPER")==null?"": String.valueOf(m.get("INMONEYPER")));
                    //流入次数
                    map.put(8,m.get("INNUMBER")==null?"": String.valueOf(m.get("INNUMBER")));
                    //流入次数比
                    map.put(9,m.get("INNUMBERPER")==null?"": String.valueOf(m.get("INNUMBERPER")));
                    //流出金额
                    map.put(10,m.get("OUTMONEY")==null?"": String.valueOf(m.get("OUTMONEY")));
                    //流出金额比
                    map.put(11,m.get("OUTMONEYPER")==null?"": String.valueOf(m.get("OUTMONEYPER")));
                    //流出次数
                    map.put(12,m.get("OUTNUMBER")==null?"": String.valueOf(m.get("OUTNUMBER")));
                    //流出次数比
                    map.put(13,m.get("OUTNUMBERPER")==null?"": String.valueOf(m.get("OUTNUMBERPER")));
                    //把map集合添加到lists集合
                    lists.add(map);
                }
                break;
            }
            case 5:{
                for (Map m : list) {
                    Map<Integer, Object> map = new HashMap<Integer, Object>();
                    //月份
                    map.put(0, m.get("MONTH")==null?"":m.get("MONTH"));
                    //交易对手卡号
                    map.put(1, m.get("ACCOUNT_RIVAL_CARD")==null?"":String.valueOf(m.get("ACCOUNT_RIVAL_CARD")));
                    //交易对手
                    map.put(2, m.get("ACCOUNT_RIVAL")==null?"":String.valueOf(m.get("ACCOUNT_RIVAL")));
                    //总金额
                    map.put(3, m.get("TOTALMONEY")==null?"":String.valueOf(m.get("TOTALMONEY")));
                    //总次数
                    map.put(4, m.get("TOTALNUMBER")==null?"":String.valueOf(m.get("TOTALNUMBER")));
                    //净流入
                    map.put(5, m.get("PUREINMONEY")==null?"":String.valueOf(m.get("PUREINMONEY")));
                    //流入金额
                    map.put(6,m.get("INMONEY")==null?"": String.valueOf(m.get("INMONEY")));
                    //流入金额比
                    map.put(7,m.get("INMONEYPER")==null?"": String.valueOf(m.get("INMONEYPER")));
                    //流入次数
                    map.put(8,m.get("INNUMBER")==null?"": String.valueOf(m.get("INNUMBER")));
                    //流入次数比
                    map.put(9,m.get("INNUMBERPER")==null?"": String.valueOf(m.get("INNUMBERPER")));
                    //流出金额
                    map.put(10,m.get("OUTMONEY")==null?"": String.valueOf(m.get("OUTMONEY")));
                    //流出金额比
                    map.put(11,m.get("OUTMONEYPER")==null?"": String.valueOf(m.get("OUTMONEYPER")));
                    //流出次数
                    map.put(12,m.get("OUTNUMBER")==null?"": String.valueOf(m.get("OUTNUMBER")));
                    //流出次数比
                    map.put(13,m.get("OUTNUMBERPER")==null?"": String.valueOf(m.get("OUTNUMBERPER")));
                    //把map集合添加到lists集合
                    lists.add(map);
                }
                break;
            }
            case 6:
            case 7:{
                for (Map m : list) {
                    Map<Integer, Object> map = new HashMap<Integer, Object>();
                    if(m.containsKey("DATETIME")){
                        map.put(0, m.get("DATETIME")==null?"":m.get("DATETIME"));
                    }else if(m.containsKey("MONTH")){
                        map.put(0, m.get("MONTH")==null?"":m.get("MONTH"));
                    }else if(m.containsKey("WEEK")){
                        map.put(0, m.get("WEEK")==null?"":m.get("WEEK"));
                    }else if(m.containsKey("HOUR")){
                        map.put(0, m.get("HOUR")==null?"":m.get("HOUR"));
                    }
                    //交易总金额
                    map.put(1, m.get("TOTALMONEY")==null?"":String.valueOf(m.get("TOTALMONEY")));
                    //交易总次数
                    map.put(2, m.get("TOTALNUMBER")==null?"":String.valueOf(m.get("TOTALNUMBER")));

                    //净流入金额
                    map.put(3, m.get("PUREINMONEY")==null?"":String.valueOf(m.get("PUREINMONEY")));
                    //流入金额
                    map.put(4, m.get("INMONEY")==null?"":String.valueOf(m.get("INMONEY")));
                    //流入金额比
                    map.put(5, m.get("INMONEYPER")==null?"":String.valueOf(m.get("INMONEYPER")));
                    //流入次数
                    map.put(6,m.get("INNUMBER")==null?"": String.valueOf(m.get("INNUMBER")));
                    //流入次数比
                    map.put(7,m.get("INNUMBERPER")==null?"": String.valueOf(m.get("INNUMBERPER")));

                   /* //净流出金额
                    map.put(3, m.get("PUREOUTMONEY")==null?"":String.valueOf(m.get("PUREOUTMONEY")));*/
                    //流出金额
                    map.put(8, m.get("OUTMONEY")==null?"":String.valueOf(m.get("OUTMONEY")));
                    //流出金额比
                    map.put(9, m.get("OUTMONEYPER")==null?"":String.valueOf(m.get("OUTMONEYPER")));
                    //流出次数
                    map.put(10,m.get("OUTNUMBER")==null?"": String.valueOf(m.get("OUTNUMBER")));
                    //流出次数比
                    map.put(11,m.get("OUTNUMBERPER")==null?"": String.valueOf(m.get("OUTNUMBERPER")));
                    //把map集合添加到lists集合
                    lists.add(map);
                }
                break;
            }
            case 8:{
                for (Map m : list) {
                    Map<Integer, Object> map = new HashMap<Integer, Object>();
                    //摘要
                    map.put(0, m.get("CONTENT_ABSTRACT")==null?"":String.valueOf(m.get("CONTENT_ABSTRACT")));
                    //交易次数
                    map.put(1, m.get("TRANSACTIONTIMES")==null?"":String.valueOf(m.get("TRANSACTIONTIMES")));
                    //交易次数比
                    map.put(2, m.get("TRANSACTIONTIMESPER")==null?"":String.valueOf(m.get("TRANSACTIONTIMESPER")));
                    //交易金额
                    map.put(3,m.get("TRANSACTIONMONEY")==null?"": String.valueOf(m.get("TRANSACTIONMONEY")));
                    //交易金额比
                    map.put(4,m.get("TRANSACTIONMONEYPER")==null?"": String.valueOf(m.get("TRANSACTIONMONEYPER")));
                    lists.add(map);
                }
                break;
            }
            case 9:{
                for (Map m : list) {
                    Map<Integer, Object> map = new HashMap<Integer, Object>();
                    //归属银行
                    map.put(0, m.get("ACCOUNT_BODY_BANK")==null?"":String.valueOf(m.get("ACCOUNT_BODY_BANK")));
                    //对方机构号
                    map.put(1, m.get("INSTITUTION_NUMBER")==null?"":String.valueOf(m.get("INSTITUTION_NUMBER")));
                    //对方机构名称
                    map.put(2, m.get("ACCOUNT_RIVAL_BANK")==null?"":String.valueOf(m.get("ACCOUNT_RIVAL_BANK")));
                    //交易次数
                    map.put(3,m.get("ACCOUNT_COUNT")==null?"": String.valueOf(m.get("ACCOUNT_COUNT")));
                    //交易次数比
                    map.put(4,m.get("MORETHAN")==null?"": String.valueOf(m.get("MORETHAN"))+"%");
                    //交易金额
                    map.put(5,m.get("MONEY")==null?"": String.valueOf(m.get("MONEY")));
                    //交易金额比
                    map.put(6,m.get("MONEYPROPORTION")==null?"": String.valueOf(m.get("MONEYPROPORTION"))+"%");
                    lists.add(map);
                }
                break;
            }
        }
        return lists;
    }


    @RequestMapping(method= RequestMethod.POST,value = "inaccountstatistics_detail")
    @ResponseBody
    public Object getInStreamAccountCount_detail(DealflowVO dealFlow){
        return transactionStreamCountService.getInStreamAccountCount_detail(dealFlow.getCasemanageId(),dealFlow, dealFlow.getPage(), dealFlow.getRows());
    }
    @RequestMapping(method= RequestMethod.POST,value = "inaccountExcel")
    @ResponseBody
    public void inaccountExcel(DealflowVO dealFlow,HttpServletResponse response )throws Exception{
        XSSFWorkbook workbook1 = new XSSFWorkbook();
        SXSSFWorkbook wb = new SXSSFWorkbook(workbook1, 100);
        //创建HSSFWorkbook对象(excel的文档对象)
        //建立新的sheet对象（excel的表单）
        Sheet sheet=wb.createSheet("交易详情");
        //在sheet里创建第二行
        Row row2=sheet.createRow(0);
        //创建单元格并设置单元格内容
        row2.createCell(0).setCellValue("交易主体");
        row2.createCell(1).setCellValue("交易主体账号");
        row2.createCell(2).setCellValue("交易主体卡号");
        row2.createCell(3).setCellValue("交易对手");
        row2.createCell(4).setCellValue("交易对手账号");
        row2.createCell(5).setCellValue("交易对手卡号");
        row2.createCell(6).setCellValue("交易时间");
        row2.createCell(7).setCellValue("交易类型");
        row2.createCell(8).setCellValue("交易金额");
        row2.createCell(9).setCellValue("交易后余额");
        row2.createCell(10).setCellValue("摘要");
        row2.createCell(11).setCellValue("对手归属行");
        row2.createCell(12).setCellValue("主体归属行");
        row2.createCell(13).setCellValue("对方机构号");
        row2.createCell(14).setCellValue("柜员号");
        row2.createCell(15).setCellValue("备注");
        //在sheet里创建第三行
        PageResult countDetail = transactionStreamCountService.getInStreamAccountCount_detail(dealFlow.getCasemanageId(), dealFlow, 1, Integer.MAX_VALUE);
        List<Map<String, Object>> content = countDetail.getRows();
        if (content!=null && content.size()>0){
            for (int i=0;i<content.size();i++){
                Map<String, Object> map = content.get(i);
                Row row3=sheet.createRow(i+1);
                row3.createCell(0).setCellValue((String)map.get("ACCOUNT_BODY"));
                row3.createCell(1).setCellValue((String)map.get("ACCOUNT_BODY_NUMBER"));
                row3.createCell(2).setCellValue((String)map.get("ACCOUNT_BODY_CARD"));
                row3.createCell(3).setCellValue((String)map.get("ACCOUNT_RIVAL"));
                row3.createCell(4).setCellValue((String)map.get("ACCOUNT_RIVAL_NUMBER"));
                row3.createCell(5).setCellValue((String)map.get("ACCOUNT_RIVAL_CARD"));
                row3.createCell(6).setCellValue(DateUtils.getDateString((Date) map.get("TRADE_DATE")));
                row3.createCell(7).setCellValue(map.get("SIGN").toString().contains("0")?"进":"出");
                row3.createCell(8).setCellValue(map.get("ACCOUNT_MONEY")==null?"0":map.get("ACCOUNT_MONEY").toString());
                row3.createCell(9).setCellValue(map.get("SURPLUS_MONEY")==null?"0":map.get("SURPLUS_MONEY").toString());
                row3.createCell(10).setCellValue((String) map.get("CONTENT_ABSTRACT"));
                row3.createCell(11).setCellValue((String) map.get("ACCOUNT_RIVAL_BANK"));
                row3.createCell(12).setCellValue((String) map.get("ACCOUNT_BODY_BANK"));
                row3.createCell(13).setCellValue((String) map.get("INSTITUTION_NUMBER"));
                row3.createCell(14).setCellValue((String) map.get("TELLER_NUMBER"));
                row3.createCell(15).setCellValue((String) map.get("REMARKS"));
            }
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = "交易详情" + dateFormat.format(new Date());
        //输出Excel文件
        OutputStream output=response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename="+ ExcelUtils.toUtf8String(fileName+".xlsx"));
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
        //添加导出日志
        dataOperationLogService.save(null, super.getLoginUser(), new PhoneRecord(), new PhoneRecord(), SystemFlag.ZD, ModuleFlag.BILLEXPORT, ActionType.EXPORT);

    }



    @RequestMapping(method= RequestMethod.POST,value = "monthAnalysis")
    @ResponseBody
    public Result monthAnalysis(@RequestBody Map whereMap){
        String caseId = request.getSession().getAttribute("caseId") == null?"":request.getSession().getAttribute("caseId").toString();
        whereMap.put("CASEMANAGE_ID",caseId);
        return new Result(true, StatusCode.OK,"查询成功",transactionStreamCountService.monthAnalysis(whereMap));
    }
    @RequestMapping(method= RequestMethod.POST,value = "monthAnalysisDetail/{page}")
    @ResponseBody
    public Result getMonthAnalysisDetail(@RequestBody Map<String,String> whereMap,@PathVariable int page){
        String caseId = request.getSession().getAttribute("caseId") == null?"":request.getSession().getAttribute("caseId").toString();
        whereMap.put("CASEMANAGE_ID",caseId);
        return new Result(true, StatusCode.OK,"查询成功",transactionStreamCountService.getMonthAnalysisDetail(whereMap,page));
    }
    @RequestMapping(method= RequestMethod.POST,value = "monthAnalysisDetail_easyui")
    @ResponseBody
    public PageResult getMonthAnalysisDetail_easyui(MonthAnalysisDto dto){
        String caseId = request.getSession().getAttribute("caseId") == null?"":request.getSession().getAttribute("caseId").toString();
        dto.setCaseId(caseId);
        PageResult pageResult = transactionStreamCountService.getMonthAnalysisDetail_easyui(dto);
        return pageResult;
    }

    @RequestMapping(method= RequestMethod.POST,value = "moneyFlowExcel")
    @ResponseBody
    public void getMoneyFlowExcel(String[] checkedAccount,String caseId,String beginTime,String endTime,Integer minMoney,Integer maxMoney,HttpServletResponse response )throws Exception{
        if (checkedAccount==null||caseId==null)return ;
        List<String> strings = Arrays.asList(checkedAccount);
        XSSFWorkbook workbook1 = new XSSFWorkbook();
        SXSSFWorkbook wb = new SXSSFWorkbook(workbook1, 100);
        //创建HSSFWorkbook对象(excel的文档对象)
        //建立新的sheet对象（excel的表单）
        Sheet sheet=wb.createSheet("相互资金流向分析");
        //在sheet里创建第二行
        Row row2=sheet.createRow(0);
        //创建单元格并设置单元格内容
        row2.createCell(0).setCellValue("主体姓名");
        row2.createCell(1).setCellValue("主体卡号");
        row2.createCell(2).setCellValue("对方姓名");
        row2.createCell(3).setCellValue("对方卡号");
        row2.createCell(4).setCellValue("交易金额");
        row2.createCell(5).setCellValue("资金流向");
        row2.createCell(6).setCellValue("交易日期");
        //在sheet里创建第三行
        Map<String, Object> moneyFlow = transactionStreamCountService.getMoneyFlow(strings, caseId, beginTime, endTime, minMoney, maxMoney);
        List<DealFlow> recordList = (List<DealFlow>)moneyFlow.get("excel");
        if (recordList!=null && recordList.size()>0){
            for (int i=0;i<recordList.size();i++){
                DealFlow dealFlow = recordList.get(i);
                Row row3=sheet.createRow(i+1);
                row3.createCell(0).setCellValue(dealFlow.getAccountBody());
                row3.createCell(1).setCellValue(dealFlow.getAccountBodyCard());
                row3.createCell(2).setCellValue(dealFlow.getAccountRival());
                row3.createCell(3).setCellValue(dealFlow.getAccountRivalCard());
                row3.createCell(4).setCellValue(dealFlow.getAccountMoney()==null?"0":dealFlow.getAccountMoney().toString());
                row3.createCell(5).setCellValue(dealFlow.getSign()==1?"收入":"转出");
                row3.createCell(6).setCellValue(DateUtils.getDateString(dealFlow.getTradeDate()));
            }
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = "相互资金流向分析" + dateFormat.format(new Date());
        //输出Excel文件
        OutputStream output=response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename="+ ExcelUtils.toUtf8String(fileName+".xlsx"));
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
        //添加导出日志
        dataOperationLogService.save(null, super.getLoginUser(), new PhoneRecord(), new PhoneRecord(), SystemFlag.HD, ModuleFlag.PHONERECORDEXPORT, ActionType.EXPORT);

    }

    @RequestMapping(method= RequestMethod.POST,value = "moneyFlowPersonalExcel")
    @ResponseBody
    public void getMoneyFlowPersonalExcel(DealFlowVo vo,HttpServletResponse response )throws Exception{
        XSSFWorkbook workbook1 = new XSSFWorkbook();
        SXSSFWorkbook wb = new SXSSFWorkbook(workbook1, 100);
        //创建HSSFWorkbook对象(excel的文档对象)
        //建立新的sheet对象（excel的表单）
        Sheet sheet=wb.createSheet("个人流向分析");
        //在sheet里创建第二行
        Row row2=sheet.createRow(0);
        //创建单元格并设置单元格内容
        row2.createCell(0).setCellValue("主体姓名");
        row2.createCell(1).setCellValue("主题卡号");
        row2.createCell(2).setCellValue("对方姓名");
        row2.createCell(3).setCellValue("对方卡号");
        row2.createCell(4).setCellValue("交易金额");
        row2.createCell(5).setCellValue("资金流向");
        row2.createCell(6).setCellValue("转账日期");
        //在sheet里创建第三行
        List<DealFlow> recordList = transactionStreamCountService.zjlxfx(vo);
        if (recordList!=null && recordList.size()>0){
            for (int i=0;i<recordList.size();i++){
                DealFlow dealFlow = recordList.get(i);
                Row row3=sheet.createRow(i+1);
                row3.createCell(0).setCellValue(dealFlow.getAccountBody());
                row3.createCell(1).setCellValue(dealFlow.getAccountBodyCard());
                row3.createCell(2).setCellValue(dealFlow.getAccountRival());
                row3.createCell(3).setCellValue(dealFlow.getAccountRivalCard());
                row3.createCell(4).setCellValue(dealFlow.getAccountMoney()==null?"0":dealFlow.getAccountMoney().toString());
                row3.createCell(5).setCellValue(dealFlow.getSign()==1?"收入":"转出");
                if(dealFlow.getTradeDate()!=null) {
                	row3.createCell(6).setCellValue(DateUtils.getDateString(dealFlow.getTradeDate()));
                }else {
                	row3.createCell(6).setCellValue("");
                }
            }
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = "资金流向分析" + dateFormat.format(new Date());
        //输出Excel文件
        OutputStream output=response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename="+ ExcelUtils.toUtf8String(fileName+".xlsx"));
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
        //添加导出日志
        dataOperationLogService.save(null, super.getLoginUser(), new PhoneRecord(), new PhoneRecord(), SystemFlag.HD, ModuleFlag.PHONERECORDEXPORT, ActionType.EXPORT);

    }
}
